<template>
  <div>
    <!-- NavBar区域 -->
    <van-nav-bar v-if="isHome" title="黑马优购"/>
    <van-nav-bar v-else title="黑马优购">
      <template #left>
        <div class="left_arrow" @click="()=>{ $router.go(-1) }">
          <van-icon name="arrow-left"/>
          <span>返回</span>
        </div>
      </template>
    </van-nav-bar>
    <!-- 路由占位符 -->
    <router-view></router-view>
    <!-- tabbar区域 -->
    <van-tabbar active-color="#d81e06" v-model="active" router>
      <van-tabbar-item name="/home" to="/home">
        <span>首页</span>
        <template #icon="props">
          <img :src="props.active ? icon.home_a : icon.home_n">
        </template>
      </van-tabbar-item>
      <van-tabbar-item name="/cates" to="/cates">
        <span>分类</span>
        <template #icon="props">
          <img :src="props.active ? icon.cates_a : icon.cates_n">
        </template>
      </van-tabbar-item>
      <van-tabbar-item name="/search" to="/search">
        <span>搜索</span>
        <template #icon="props">
          <img :src="props.active ? icon.search_a : icon.search_n">
        </template>
      </van-tabbar-item>
      <van-tabbar-item name="/cart" to="/cart" :badge="$store.getters.totalNum">
        <span>购物车</span>
        <template #icon="props">
          <img :src="props.active ? icon.cart_a : icon.cart_n">
        </template>
      </van-tabbar-item>
      <van-tabbar-item name="/my" to="/my">
        <span>我的</span>
        <template #icon="props">
          <img :src="props.active ? icon.my_a : icon.my_n">
        </template>
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
export default {
  data() {
    return {
      active: "/home", // 默认被选中的项
      icon: {
        // tabbar组件自定义icon图片的数据源
        home_n: "icons/home.png",
        home_a: "icons/home-active.png",
        cates_n: "icons/cates.png",
        cates_a: "icons/cates-active.png",
        search_n: "icons/search.png",
        search_a: "icons/search-active.png",
        cart_n: "icons/cart.png",
        cart_a: "icons/cart-active.png",
        my_n: "icons/my.png",
        my_a: "icons/my-active.png"
      }
    };
  },
  // 在created生命周期函数中 获取当前的路由path 给到 this.active 来确定被选中的是哪一个tabbar
  created() {
    this.active = this.$route.path;
  },
  computed: {
    isHome: function() {
      if (this.$route.path == "/" || this.$route.path == "/home") {
        return true;
      } else {
        return false;
      }
    }
  },
  // 设置侦听器，侦听路由变化，这种方式也可以解决导航菜单激活问题
  // 也可以解决浏览器前进后退哈希值变化，而激活菜单不跟着变化的bug
  watch: {
    "$route.path": function(value) {
      this.active = value;
    }
  }
};
</script>

<style lang="less" scoped>
</style>